import 'dart:io';
import 'dart:convert';
import 'package:car_map/mode/net_model/project_list_entity.dart';
import 'package:car_map/net/request.dart';
import 'package:dio/dio.dart';
import 'api.dart';
import 'base_dto.dart';
import 'interceptor.dart';

class RequestImpl extends Request {
  static Dio _dio;

  RequestImpl() : super.internal() {
    Options options = Options(baseUrl: Apis.baseUrl, connectTimeout: 10000);
    _dio = Dio(options);
    _dio.options.contentType =
        ContentType.parse("application/x-www-form-urlencoded");
    LogInterceptor interceptor = LogInterceptor();
    _dio.interceptor.request.onSend = interceptor.onSend;
    _dio.interceptor.response.onSuccess = interceptor.onSuccess;
    _dio.interceptor.response.onError = interceptor.onError;

//    _setPersistCookieJar();
  }

//  _setPersistCookieJar() async {
//    Directory dir = await getApplicationDocumentsDirectory();
//    String path = dir.path;
//    _dio.cookieJar = new PersistCookieJar(dir: path);
//  }

  static _handleRes(Response response) {
    Map<String, dynamic> resJson;
    if (response.data is String) {
      resJson = json.decode(response.data);
      ;
    } else if (response.data is Map<String, dynamic>) {
      resJson = response.data;
    } else {
      throw DioError(message: '数据解析错误');
    }
    BaseDTO base = BaseDTO.fromJson(resJson);
    if (base.errorCode == 0) {
      return base.data;
    } else {
      throw DioError(message: base.errorMsg);
    }
  }

  @override
  Future<List<ProjectListEntity>> getProjectListData(String organId) async{
    // TODO: implement getSubscriptions
    Response response = await _dio.post(Apis.projectList,
        data: FormData.from({
          'organId':'${organId}',
        }));
    List<ProjectListEntity> data = new List<ProjectListEntity>();
    _handleRes(response).forEach((v) {
      data.add(new ProjectListEntity.fromJson(v));
    });
    return data;
  }

}